package com.cyj.comment.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.cyj.comment.utils.RedisConstants.*;

/**
 * @ClassName CacheClient
 * @Description TODO
 * @Author chixiaowai
 * @Date 2023/4/7 18:53
 * @Version 1.0
 */
@Component
@Slf4j
public class CacheClient {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    public void setWIthLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 缓存穿透
     * @param keyPrefix key的前缀
     * @param id
     * @param type
     * @param dbFallback
     * @param <R>
     * @param <ID>
     * @return
     */
    public <R, ID> R queryShopWithPassThrough(
            String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit){
        //1、从redis中查询商铺缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        //2、判断缓存是否命中
        if (StrUtil.isNotBlank(json)) {
            //3、命中就返回
            return JSONUtil.toBean(json, type);
        }

        //判断在缓存中是否命中空值
        if (json != null){
            //命中空值返回错误信息
            return null;
        }
        // TODO 布隆过滤器
        //4、缓存中不存在查询数据库
        R r = dbFallback.apply(id);
        //5、数据库中不存在将空值写入redis中并返回错误提示
        if (r == null){
            //解决缓存穿透
            //将空值写入redis
            this.set(key, "", time, unit);
            return null;
        }
        //6、存在，写入redis并返回
        this.set(key, JSONUtil.toJsonStr(r), time + new Random().nextInt(10), unit);
        return r;
    }

    /**
     * 缓存击穿-逻辑过期
     * @param id
     * @return
     */
    public <R, ID> R queryShopLogicalExpire(
            String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit){
        //1、从redis中查询商铺缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        //2、判断缓存是否命中
        if (StrUtil.isBlank(json)) {
            //3、未命中直接返回
            return null;
        }
        //4、命中，需要将json反序列化
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(data, type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5、判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())){
            //未过期，直接返回商铺信息
            return r;
        }
        //6、已过期，需要缓存重建
        //6.1、获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        //6.2、判断互斥锁是否获取成功
        if (isLock){
            //获取锁成功后需要再次检测缓存是否过期，未过期则直接返回
            if(expireTime.isAfter(LocalDateTime.now())){
                return r;
            }
            //6.3、成功，开启独立线程，进行缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //查询数据库
                    R r1 = dbFallback.apply(id);

                    if (r1 == null){
                        this.set(key, "", time, unit);
                    }
                    setWIthLogicalExpire(key, r1, time, unit);
                    //写入redis
//                    this.set(key, r1, time + new Random().nextInt(10), unit);
                } catch (Exception e) {
                    throw new RuntimeException();
                }finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }
        //6.4、返回过期商铺信息
        return r;
    }

    /**
     * 获取互斥锁
     * @param key
     * @return
     */
    public boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     * @param key
     */
    public void unLock(String key){
        stringRedisTemplate.delete(key);
    }

}
